package com.dushibao.manage;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

@WebServlet(name = "DownLoadServlet",urlPatterns = "/DownLoadServlet")
public class DownLoadServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        //获得此servlet对象， 得到文件的路径
        //String path = this.getServletContext().getRealPath("/WEB-INF/classes/图片.jpg");
        String path = "C:/aServer/java.png";
        //创建字节输入流
        FileInputStream in = new FileInputStream(path);
        //得到下载的文件名
        String filename = "a.png";//path.substring(path.lastIndexOf("\\")+1);//找到最后的\然后取后面的文件名
        //设置文件编码
        filename = URLEncoder.encode(filename, "UTF-8"); //转成utf-8 ，返回String

        //创建字节输出流
        OutputStream out = response.getOutputStream(); //此方法获取输出流对象

        //告知客户端下载文件
        //启动下载
        //规定后缀名
        response.setHeader("content-disposition", "attachment;filename="+filename);
        //response.setHeader("content-type","image/jpeg");

        //执行输出操作
        int len = 1;
        byte[] b = new byte[1024];
        while ((len=in.read(b))!=-1){
            out.write(b,0,len);
            //out.write(len);与上面的区别
        }
        out.close();
        in.close();
    }

}

